package com.example.rbac.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {
    
    @Value("${jwt.secret}")
    private String secret;
    
    @Value("${jwt.expiration}")
    private long expiration;
    
    // 安全密钥对象，用于签名和验证
    private Key signingKey;
    
    // 初始化时创建符合JWA规范的密钥
    @PostConstruct
    public void init() {
        // 使用Keys.secretKeyFor创建符合JWA规范的密钥
        // 这将确保密钥大小至少为256位
        signingKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
    }
    
    // 生成token
    public String generateToken(Long userId, String username, Map<String, Object> claims) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .claim("userId", userId)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(signingKey, SignatureAlgorithm.HS512).compact();
    }
    
    // 解析token
    public Claims parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(signingKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (io.jsonwebtoken.MalformedJwtException e) {
            throw new RuntimeException("无效的JWT令牌格式", e);
        } catch (io.jsonwebtoken.SignatureException e) {
            throw new RuntimeException("JWT签名验证失败", e);
        } catch (io.jsonwebtoken.ExpiredJwtException e) {
            throw new RuntimeException("JWT令牌已过期", e);
        } catch (io.jsonwebtoken.UnsupportedJwtException e) {
            throw new RuntimeException("不支持的JWT令牌", e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("JWT令牌为空或格式错误", e);
        }
    }
    
    // 从token中获取用户ID
    public Long getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return Long.parseLong(claims.get("userId").toString());
    }
    
    // 从token中获取用户名
    public String getUsernameFromToken(String token) {
        return parseToken(token).getSubject();
    }
    
    // 检查token是否过期
    public boolean isTokenExpired(String token) {
        Date expiration = parseToken(token).getExpiration();
        return expiration.before(new Date());
    }
    
    // 验证token
    public boolean validateToken(String token, String username) {
        String tokenUsername = getUsernameFromToken(token);
        return (username.equals(tokenUsername) && !isTokenExpired(token));
    }
}